﻿using DotNetStar.TheKing.Infrastructure;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using SDDP;
using System;
using System.Collections.Generic;
using System.Text;

namespace DotNetStar.TheKing.Domain.EventHandlers
{
    public class TradingPointTransitionEventHandler : EventHandlerBase<TradingPointTransitionEventHandler>, IEventHandler<TradingPointTrasitionEvent>
    {
        IStorage<User, long> _userStorage;
        private IStorage<UserPointHistory, Guid> _userPointListStorage;
        public TradingPointTransitionEventHandler(ILoggerFactory loggerFactory, IMemoryCache memoryCache
            , IStorage<User, long> userStorage
            ,IStorage<UserPointHistory, Guid> userPointListStorage
            ) 
            : base(loggerFactory, memoryCache)
        {
            this._userStorage = userStorage;
            _userPointListStorage = userPointListStorage;
        }

        public void Handle(TradingPointTrasitionEvent e)
        {
            if (e.FromUserId>0)
            {
                var fromUser = _userStorage.GetById(e.FromUserId);
                if (fromUser.TradingPoints < e.TransitionPoints)
                {
                    throw new ArgumentOutOfRangeException($"{fromUser.UserName}积分不足");
                }

                fromUser.IncreaseTradingPoint(-e.TransitionPoints);

                _userStorage.Context.Commit();



                var point = new UserPointHistory
                {
                    UserId = e.FromUserId,
                    PointStrategyId = "",
                    TradingPoints =-e.TransitionPoints,
                    Remark = $"{e.Title} 金币 {(-e.TransitionPoints).GetPositiveNumString()}"
                };

                _userPointListStorage.Add(point);
                _userPointListStorage.Context.Commit();

                base.Cache.Set(UserPointHistory.GetUserPointCacheKey(e.FromUserId), point, DateTimeOffset.Now.AddSeconds(30));

            }

            if (e.ToUserId > 0)
            {
                var toUser = _userStorage.GetById(e.ToUserId);
                toUser.IncreaseTradingPoint(e.TransitionPoints);

                _userStorage.Context.Commit();


                var point = new UserPointHistory
                {
                    UserId = e.ToUserId,
                    PointStrategyId = "",
                    TradingPoints = e.TransitionPoints,
                    Remark = $"{e.Title} 金币 {(e.TransitionPoints).GetPositiveNumString()}"
                };

                _userPointListStorage.Add(point);
                _userPointListStorage.Context.Commit();

                //base.Cache.Set(UserPointHistory.GetUserPointCacheKey(e.ToUserId), point, DateTimeOffset.Now.AddSeconds(30));
            }



        }
    }
}
